<template>
	<view>
		<cu-custom :isBack="true" :bgColor="'bg-'+ theme.themeColor">
			<block slot="backText">返回</block>
			<block slot="content">订单确认</block>
		</cu-custom>
		<view class="bg-white radius-xl margin-sm">
			<view hover-class="none" url="">
				<view class="cu-list menu-avatar">
					<view class="cu-item" @tap="routerlink" v-if="!hasSubscribeTime" >
							<view class="cu-avatar bg-white text-xxl" :class="'text-'+ theme.themeColor">
								<text class="cuIcon-location" style="font-size: 30px;"></text>
							</view>
							<view v-if="addressInfo.id" class="content letstyle" style="letter-spacing: 0;margin-top: 5px;">
								<view class="text-gray text-sm flex">
									<view class="text-cut" style="font-size: 16px;color: #000;">
										{{addressInfo.provinceName}}  {{addressInfo.countyName}} {{addressInfo.detailAddress}} 
									</view>
								</view>
								<view style="color: #333;font-size: 13px;">{{addressInfo.addresseeName}} <text style="font-size: 13px;color: #999;margin-left: 10px;">{{addressInfo.telephone}}</text></view>
								
							</view>
							<view class="content letstyle" v-else>
								<text class="text-bold">请选择收货地址</text>
							</view>
							<view class="action">
								<text class="cuIcon-right"></text>
							</view>
					</view>
					<view class="cu-item-catainer" v-else>
						<view class="cu-avatar bg-white text-xxl" :class="'text-'+ theme.themeColor">
							<text class="cuIcon-location" style="font-size: 40px;"></text>
						</view>
						<view class="cu-item-con">
							<text class="text-mstitle">美诗国际(望城总店)</text>
							<text class="text-titlexq">长沙市望城区高塘岭街道92号</text>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="bg-white radius-xl margin-sm">
			<view v-for="(item,index) in orderInfo.placeOrderSkus" class="flex">
				<view class="basis-xs margin-xs radius">
					<view class="cu-avatar radius xl" :style="'background-image:url(' + item.picUrl + ')'">
					</view>
				</view>
				<view class="basis-xl padding-sm radius">
					<view class="hx-overflow-2 text-bold">
						{{item.spuName}}
					</view>
					<view v-if="item.specsInfo">
						{{item.specsInfo}}
					</view>
					<view class="flex justify-between align-end padding-top-xs">
						<view class="text-bold text-df text-price" :class="'text-'+theme.themeColor">{{item.salesPrice}}
						</view>
						<view> x{{item.buyQuantity}}</view>
					</view>
				</view>
			</view>
			<view class="cu-bar bg-white">
				<view class="action">
					<text class="cuIcon-title " :class="'text-'+ theme.matchColor"></text> 商品金额
				</view>
				<view class="action">
					<view class="text-price">{{orderInfo.totalPrice}}</view>
				</view>
			</view>
			
			<!-- 优惠券 -->
			<view class="cu-bar bg-white">
				<view class="action">
					<text class="cuIcon-title" :class="'text-'+ theme.matchColor"></text> 优惠券
					<text class="cu-tag radius line-red sm margin-left-xs" :class="'text-'+theme.themeColor"
						v-if="selectedCoupon.id">{{selectedCoupon.couponInfo.couponName}}</text>
				</view>
				<view class="action">
					<view v-if="userCouponList.length>0" class="text-sm" :class="'text-'+theme.themeColor"
						@tap="couponModal=true">
						<text>{{orderInfo.couponPrice >0 ? '- ￥'+orderInfo.couponPrice :'选择券'}}</text><text
							class="cuIcon-right"></text>
					</view>
					<view v-else>无优惠券</view>
				</view>
			</view>
			
			<coupon-confirm :couponUserList="userCouponList" :couponModal="couponModal"
				@changeCouponModal="couponModal=$event" :orderInfo="orderInfo" @changeOneCoupon="changeOneCoupon">
			</coupon-confirm>
			<view class="cu-bar bg-white solid-bottom">
				<view class="action">
					<text class="cuIcon-title" :class="'text-'+ theme.matchColor"></text> 订单备注
				</view>
				<view class="action">
					<view>
						<input placeholder="请输入订单备注" class="text-right" name="input"></input>
					</view>
				</view>
			</view>
		</view>
		<view class="cu-tabbar-height"></view>
		<!-- 底部操作栏 -->
		<view class="cu-bar bg-white tabbar foot">
			<view class="flex padding justify-between" style="width: 100%;">
				<view>
					<text class="text-price text-xxl" :class="'text-'+theme.themeColor"
						v-if="orderInfo.paymentPrice">{{orderInfo.paymentPrice}}</text>
				</view>
				<view>
					<button class="cu-btn shadow round" @tap="createOrderSub" :class="'bg-'+ theme.themeColor"
						data-target="menuModal">提交订单</button>
				</view>
			</view>
		</view>
	</view>

</template>

<script>
	import {
		getPage as getUserCouponPage
	} from '@/api/couponuser.js';
	import {
		createOrder
	} from '@/api/orderinfo.js';
	import {
		defaultAddress
	} from '@/api/useraddress.js';
	import couponConfirm from '@/components/coupon-confirm/index.vue';
	import store from '@/store/index'; // store
	export default {
		components: {
			couponConfirm
		},
		data() {
			return {
				theme: getApp().globalData.theme,
				remark: '',
				showRemark: false,
				orderInfo: {
					orderType: '1', // 订单类型：订单类型：1.普通订单；2.多人拼团;
					deliveryWay: '1', // 配送方式：1.普通快递；2.上门自提
					deliveryWay: '1',
					orderItemList: []
				},
				addressInfo: {},
				spuIds: [],
				goodsList: [], // 商品数组
				userCouponList: [],
				couponModal: false,
				selectedCoupon: {},
				freightTotalCount: {},
				type : ''
			}
		},
		onShow() {
			this.getPreOrder();
			this.getDefaultAddress();
		},
		computed: {
		  // 判断购物车列表数据中是否所有元素的 subscribeTime 属性都不为 null
		  hasSubscribeTime() {
		    return this.goodsList.every(item => item.subscribeTime !== null);
		  }
		},
		onLoad(option) {
			getApp().initPage().then(res => {
				this.getDefaultAddress();
				this.orderInfo.orderType = '1';	
			})
			
			this.type = option.type
			this.goodsList = uni.getStorageSync('goods_list') || [];
			console.log(this.goodsList)

		},
		methods: {
			routerlink(){
				// /pages/user/user-address/index?isChoose=true
				uni.navigateTo({
					url:`/pages/user/user-address/index?isChoose=${true}`
				})
				
			},
			freightCompute(freightTemplate, quantity) {
				let freightPrice = 0;
				let freightTotalCountValue = 0;
				if (this.freightTotalCount[freightTemplate.id] > 0) {
					freightTotalCountValue = this.freightTotalCount[freightTemplate.id]
				}
				this.freightTotalCount[freightTemplate.id] = freightTotalCountValue + quantity
				// 首件（个） 首重（kg）
				let firstNum = freightTemplate.firstNum;
				// 续件（个） 续重（kg）
				let continueNum = freightTemplate.continueNum;
				//首费（元）
				let firstFreight = freightTemplate.firstFreight;
				//续费（元）
				let continueFreight = freightTemplate.continueFreight;
				if (quantity <= firstNum) {
					freightPrice = firstFreight;
					// if (freightTotalCountValue <= 0) {
					// 	freightPrice = firstFreight;
					// }
					if (freightTotalCountValue > 0) {
						freightPrice = 0;
					}
				} else {
					// 续件数量
					let continueCount = quantity - firstNum;
					if (freightTotalCountValue >= firstNum) {
						continueCount = quantity - freightTotalCountValue
					}
					// 续件价格
					let continueFreightPrice = continueCount / continueNum * continueFreight
					if (freightTotalCountValue >= firstNum) {
						freightPrice = continueFreightPrice;
					} else {
						freightPrice = continueFreightPrice + firstFreight;
					}
				}
				return freightPrice;
			},
			getPreOrder() {
				let totalPrice = 0; // 商品总金额
				let freightPrice = 0; // 运费
				let couponPrice = 0; //优惠金额
				let paymentPrice = 0; // 支付金额
				let placeOrderSkus = [];
				this.spuIds = [];
				this.goodsList.forEach((item, index) => {
					if (this.spuIds) {
						this.spuIds = this.spuIds + ',' + item.spuId;
					} else {
						this.spuIds = item.spuId;
					}

					// 运费模板
					let freightTemplate = item.freightTemplate;
					let itemFreightPrice = 0;
					//计价方式：1.按件数、2.按重量、3.按体积
					switch (freightTemplate.pricingType) {
						case '1':
							itemFreightPrice = this.freightCompute(freightTemplate, item.quantity);
							break
						case '2':
							itemFreightPrice = this.freightCompute(freightTemplate, item.weight * item.quantity);
							break
						case '3':
							itemFreightPrice = this.freightCompute(freightTemplate, item.volume * item.quantity);
							break
					}
					let pricingType = freightTemplate.pricingType;
					// 商品销售价*购买数量
					let itemTotalPrice = item.salesPrice * item.quantity;
					let itemCouponPrice = 0;
					placeOrderSkus.push({
						spuId: item.spuId,
						picUrl: item.picUrl,
						spuName: item.spuName,
						buyQuantity: item.quantity,
						salesPrice: item.salesPrice,
						totalPrice: itemTotalPrice,
						freightPrice: itemFreightPrice,
						couponPrice: 0,
						paymentPrice: itemTotalPrice + itemFreightPrice,
						specsInfo: item.specsInfo,
						skuId: item.skuId,
						subscribeTime : item.subscribeTime
					})
					totalPrice += itemTotalPrice;
					paymentPrice += itemTotalPrice + itemFreightPrice;
					freightPrice += itemFreightPrice;
					couponPrice += itemCouponPrice;
				})
				this.orderInfo.placeOrderSkus = placeOrderSkus;
				this.orderInfo.salesPrice = 0; //准备废弃
				this.orderInfo.totalPrice = totalPrice.toFixed(2);
				this.orderInfo.couponPrice = couponPrice.toFixed(2);
				this.orderInfo.freightPrice = freightPrice.toFixed(2);
				this.orderInfo.paymentPrice = paymentPrice.toFixed(2);
				this.getUserCoupon(); // 查询优惠券
			},
			getUserCoupon() {
				getUserCouponPage({
					current: 1,
					size: 100,
					descs: "create_time",
					status: "0",
					spuIds: this.spuIds
				}).then(res => {
					this.userCouponList = res.data.records
				});
			},
			/**
			 * 获取默认收货地址
			 */
			async getDefaultAddress() {
				// const { data } = await defaultAddress()
				// console.log(data)
				// if(data !== null){
				// 	this.addressInfo = data
				// }
				
				defaultAddress().then(res => {
					if(res.data !== null){
						this.addressInfo = res.data
					}
				})
			},
			createOrderSub() {
				if(!this.hasSubscribeTime){
					if (Object.keys(this.addressInfo).length === 0) {
						uni.showToast({
							title: '请选择收获地址',
							icon: 'none',
							duration: 3000
						});
						return
					}
					this.onderInfo()
				}else{
					
					this.onderInfo()
				}
				
			},
			onderInfo(){
				this.orderInfo.deliveryWay = '1'; //配送方式：1.普通快递；2.上门自提
				// this.orderInfo.userAddressId = this.addressInfo.id;
				
				if (this.addressInfo && this.addressInfo.id) {
				   this.orderInfo.userAddressId = this.addressInfo.id;
			    } else {
			  	   this.orderInfo.userAddressId = null;
			    }
				
				this.orderInfo.createWay = this.type;
				
				// console.log(this.orderInfo.createWay + '')
				
				this.orderInfo.couponUserId = this.selectedCoupon.id
				
				this.orderInfo.subscribeTime = '123'
				
				console.log(this.goodsList[0].subscribeTime)
				
				
				// console.log(this.orderInfo)
				
				createOrder(this.orderInfo).then(res => {
					uni.redirectTo({
						url: '/subpkg/order/order-pay/index?id=' + res.data.id
					})
				})
			},
			setUserAddress(data) {
				this.addressInfo = data;
			},
			changeOneCoupon(coupon) {
			  if (coupon !== this.selectedCoupon) { // 检查是否选择了不同的优惠券
			    this.selectedCoupon = coupon;
			    if (coupon) {
			      const orderInfo = this.orderInfo;
			      let salesPrice = orderInfo.totalPrice - orderInfo.freightPrice;
			      let couponAmount = 0;
			      let couponInfo = coupon.couponInfo;
			      if (couponInfo.couponType == '1') { // 满减券
			        couponAmount = couponInfo.amount;
			      } else if (couponInfo.couponType == '2') { // 折扣券
			        // const discount = couponInfo.discount / 10
					const discount = (1.0 - couponInfo.discount) / 10
			        couponAmount = salesPrice * discount;
			      }
			      let couponPaymentPrice = this.orderInfo.totalPrice - couponAmount;
			      if (couponPaymentPrice < 0) {
			        this.orderInfo.paymentPrice = orderInfo.freightPrice;
			      } else {
			        this.orderInfo.paymentPrice -= couponAmount.toFixed(2);
			      }
			      this.orderInfo.couponPrice = couponAmount.toFixed(2);
			    } else {
			      this.getPreOrder();
			    }
			  }
			}
		}
	}
</script>

<style lang="scss">
	.cu-list.menu-avatar>.cu-item>.cu-avatar{
		left: 5px;
	}
	.text-mstitle{
		font-size: 13px;
		color: #303133;;
	}
	.text-titlexq{
		color: #B2B2B2;
		font-size: 12px;
		margin-top: 5px;
	}
	.cu-item-con{
		margin-left: 10px;
	}
	.cu-item-catainer{
		display: flex;
		padding-right: 5px;
		padding-left: 10px;
		height: 72px;
		background-color: #ffffff;
		align-items: center;
	}
	.cu-item-con{
		display: flex;
		flex-direction: column;
	}
	.letstyle{
		left: 42px !important;
		letter-spacing: 1px;
	}
	.yhj-con{
		background: red;
	}
</style>
